package test.n00500;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static utils.Tools.listOf;

public class Problem00600 {
    public static void main(String[] args) {
        println(3, 3);
        println(4, 9);
        println(3, 1);
    }

    public static void println(int n, int k) {
        Solution ss = new Solution();
        System.out.println(listOf(n) + "," + listOf(ss.getPermutation(n, k)));
    }

    public static class Solution {

        /**
         * 给出集合 [1,2,3,...,n]，其所有元素共有 n! 种排列。
         * <p>
         * 按大小顺序列出所有排列情况，并一一标记，当 n = 3 时, 所有排列如下
         *
         * @param n
         * @param k
         * @return
         */
        public String getPermutation(int n, int k) {
            int[] array = new int[n];
            for (int i = 0; i < n; i++) {
                array[i] = i + 1;
            }

            List<List<Integer>> result = new ArrayList<>();
            dfs(array, n, 0, new ArrayList<>(), result);
            return String.join("", result.get(k - 1).stream().map(String::valueOf).collect(Collectors.toList()));
        }

        private void dfs(int[] array, int length, int depth, List<Integer> path, List<List<Integer>> result) {
            if (depth == length) {
                result.add(new ArrayList<>(path));
                return;
            }

            for (int i = 0; i < length; i++) {
                if (path.contains(array[i])) {
                    continue;
                }
                path.add(array[i]);
                dfs(array, length, depth + 1, path, result);
                path.remove(path.size() - 1);
            }
        }
    }
}
